package com.definity.toolkit.web.taglib;

import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;

public class CheckBoxListTag extends BaseTag {

	private static final long serialVersionUID = 1720907603114519882L;

	private String propertyName;
	private String list;
	private String itemLabel;
	private String itemValue;
	private Collection<Object> value;
	
	public CheckBoxListTag() {

	}
	
	public void setPropertyName(String propertyName) {
		this.propertyName = propertyName;
	}
	
	public void setList(String list) {
		this.list = list;
	}
	
	public void setItemLabel(String itemLabel) {
		this.itemLabel = itemLabel;
	}
	
	public void setItemValue(String itemValue) {
		this.itemValue = itemValue;
	}
	
	public void setValue(Collection<Object> value) {
		this.value = value;
	}
	
	@Override
	public int doEndTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		
		Collection<?> domainList = (Collection<?>) request.getAttribute(list);
		
		Collection<Object> valueList = (Collection<Object>) value;
		
		StringBuilder html = new StringBuilder();
		html.append("<ul " + createStyleClass("checkbox-list") + " id=\"" + id + "\">");
		
		int count = 0;
		for (Object domain : domainList) {
			Object radioValue = getValue(domain, itemValue);
			
			String checked = "";
			if (valueList != null && contains(valueList, itemValue, radioValue))
				checked = "checked";
			
			html.append("<li>");
			html.append("<input type=\"checkbox\" name=\"" + propertyName + "[" + count++ + "]." + itemValue + "\" value=\"" + radioValue + "\" " + checked + " />");

			html.append("<label>");
			html.append(getValue(domain, itemLabel));
			html.append("</label>");
			html.append("</li>");
		}
		html.append("</ul>");
		
		write(html);
		
		return super.doEndTag();
	}

	private boolean contains(Collection<Object> valueList, String itemValue, Object radioValue) throws JspException {
		if (radioValue == null)
			return false;
		
		for (Object item : valueList) {
			Object value = getValue(item, itemValue);
			if (radioValue.equals(value))
				return true;
		}
		
		return false;
	}

}
